/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.report.statistics.riskanddanger;

import com.koron.common.bean.DepartmentTreeBean;
import com.koron.common.domain.KpiStatistics;
import com.koron.common.mapper.KpiStatisticsMapper;
import com.koron.common.web.Util;
import com.koron.hazardsource.mapper.IndicationItemsMapper;
import com.koron.purpose.domain.KPITemplate;
import com.koron.purpose.mapper.KPITemplateMapper;
import com.koron.report.bean.riskanddanger.DangerRectificationStatistics;
import com.koron.report.management.StatisticsManagement;
import com.koron.report.mapper.DangerRectificationStatisticMapper;
import com.koron.report.statistics.StatisticsService;
import com.koron.risk.bean.CorpBean;
import com.koron.risk.service.api.CorpManagementService;
import com.koron.risk.service.api.GridNodeService;
import com.koron.system.domain.District;
import com.koron.system.domain.DistrictCorpRelation;
import com.koron.system.mapper.DistrictMapper;
import com.koron.system.service.api.DistrictService;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.swan.bean.MessageBean;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 隐患整改率统计
 */
@Service("DangerRectificationStatisticsService")
public class DangerRectificationStatisticsServiceImpl implements StatisticsService, InitializingBean {

    private final static  Logger logger=LoggerFactory.getLogger(DangerRectificationStatisticsServiceImpl.class);

    @Autowired
    private StatisticsManagement statisticsManagement;

    @Autowired
    private Util util;

    @Autowired
    private CorpManagementService corpManagementService;

    @Autowired
    private GridNodeService gridNodeService;

    @Autowired
    private DistrictService districtService;
    @Override
    public void afterPropertiesSet() throws Exception {
        Set<Object> handlers = statisticsManagement.getHandlers();
        handlers.add(this);
    }

    @Override
    public void statisticsMonth(int year, int month) {
        try{
            //设置好时间
            Calendar calendar=Calendar.getInstance();
            calendar.set(year, month-1,1,0,0,0);
            Date startTime=calendar.getTime();
            calendar.set(year, month,1,0,0,0);
            Date endTime=calendar.getTime();
            //分别执行隐患实际整改总数，隐患计划整改总数，隐患整改率，
            rectificationFinished(1,startTime,endTime);
            rectificationTotal(1,startTime,endTime);
            rectificationRate(1,startTime,endTime);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
        }
    }

    @Override
    public void statisticsQuarter(int year, int quarter) {
        //设置好时间
      try{
          Calendar calendar=Calendar.getInstance();
          int month=0;
          switch (quarter){
              case 1:
                  break;
              case 2:
                  month=3;
                  break;
              case 3:
                  month=6;
                  break;
              case 4:
                  month=9;
                  break;
              default:
                  break;
          }
          calendar.set(year, month,1,0,0,0);
          Date startTime=calendar.getTime();
          calendar.set(year, month+2,1,0,0,0);
          Date endTime=calendar.getTime();
          //分别执行隐患实际整改总数，隐患计划整改总数，隐患整改率，
          rectificationFinished(2,startTime,endTime);
          rectificationTotal(2,startTime,endTime);
          rectificationRate(2,startTime,endTime);
      }catch (Exception e){
          logger.error(e.getMessage(),e);
          logger.error(e.getMessage(),e);
      }

    }
    @Override
    public void statisticsYear(int year) {
        try{
            //设置好时间
            Calendar calendar=Calendar.getInstance();
            calendar.set(year, 0,1,0,0,0);
            Date startTime=calendar.getTime();
            calendar.set(year+1, 0,1,0,0,0);
            Date endTime=calendar.getTime();
            //分别执行隐患实际整改总数，隐患计划整改总数，隐患整改率，
            rectificationFinished(3,startTime,endTime);
            rectificationTotal(3,startTime,endTime);
            rectificationRate(3,startTime,endTime);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
        }

    }


    /**
     * 隐患整改实际完成总数,指标库code为0077
     * @param type 日期类型，1代表是月份，2代表是季度，3代表是年
     * @param startTime 统计的开始时间
     * @param endTime 统计的结束时间
     */
    private void rectificationFinished(Integer type,Date startTime,Date endTime){
        SessionFactory factory=null;
        try{
            factory=new SessionFactory();
            KpiStatisticsMapper statisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
            IndicationItemsMapper itemsMapper=factory.getMapper(IndicationItemsMapper.class);
            //查询已整改的指标字典数据的id
            String alreadyReformId=itemsMapper.matchIndicationItems("隐患整改状态","已整改")==null?null:
                    itemsMapper.matchIndicationItems("隐患整改状态","已整改").getId();
            if(StringUtils.isEmpty(alreadyReformId)){
                return ;
            }
            //根据类型获取时间值
            String dataValue=getDateValue(type,startTime);
            //先删除当前时间值下的所有关于隐患整改的际完成总数的统计数据，不份统计层级
            Integer del=statisticsMapper.delete("0077",dataValue,null);
            //在按统计层级执行新增操作
            //统计层级为员工
            rectificationFinishedOrTotalByPerson(factory,type,startTime,endTime,alreadyReformId,"0077");
            //统计层级为部门
            rectificationFinishedOrToTalByDept(factory,type,startTime,endTime,alreadyReformId,"0077");
            //统计层级为水司
            rectificationFinishedOrTotalByCorp(factory,type,startTime,endTime,alreadyReformId,"0077");
            //统计层级为片区
            rectificationFinishedOrToTalByDistrict(factory,type,startTime,endTime,alreadyReformId,"0077");
            //统计层级为集团
            rectificationFinishedOrTotalByGroup(factory,type,startTime,endTime,alreadyReformId,"0077");
            factory.close();
        }catch (Exception e){
            if (null!=factory)
                factory.close(false);
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
        }
    }

    /**
     * 隐患整改计划完成总数,指标库code为0078
     * @param type 日期类型，1代表是月份，2代表是季度，3代表是年
     * @param startTime 统计的开始时间
     * @param endTime 统计的结束时间
     */
    private void rectificationTotal(Integer type,Date startTime,Date endTime){
        SessionFactory factory=null;
        try{
            factory=new SessionFactory();
            KpiStatisticsMapper statisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
            IndicationItemsMapper itemsMapper=factory.getMapper(IndicationItemsMapper.class);
            //根据类型获取时间值
            String dataValue=getDateValue(type,startTime);
            //先删除当前时间值下的所有关于隐患整改的际完成总数的统计数据，不份统计层级
            Integer del=statisticsMapper.delete("0078",dataValue,null);
            //在按统计层级执行新增操作
            //统计层级为员工
            rectificationFinishedOrTotalByPerson(factory,type,startTime,endTime,null,"0078");
            //统计层级为部门
            rectificationFinishedOrToTalByDept(factory,type,startTime,endTime,null,"0078");
            //统计层级为水司
            rectificationFinishedOrTotalByCorp(factory,type,startTime,endTime,null,"0078");
            //统计层级为片区
            rectificationFinishedOrToTalByDistrict(factory,type,startTime,endTime,null,"0078");
            //统计层级为集团
            rectificationFinishedOrTotalByGroup(factory,type,startTime,endTime,null,"0078");
            factory.close();
        }catch (Exception e){
            if (null!=factory)
                factory.close(false);
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
        }
    }

    /**
     * 隐患整改率
     */
    private void rectificationRate(Integer type,Date startTime,Date endTime){
        SessionFactory factory=null;
        try{
            factory=new SessionFactory();
            KpiStatisticsMapper statisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
            IndicationItemsMapper itemsMapper=factory.getMapper(IndicationItemsMapper.class);
            //根据类型获取时间值
            String dataValue=getDateValue(type,startTime);
            //先删除当前时间值下的所有关于隐患整改率总数的统计数据，不份统计层级
            Integer del=statisticsMapper.delete("0034",dataValue,null);
            //在按统计层级执行新增操作
            //统计层级为员工
            rectificationRateByPerson(factory,type,startTime,endTime);
            //统计层级为部门
            rectificationRateByDept(factory,type,startTime,endTime);
            //统计层级为水司
            rectificationRateByCorp(factory,type,startTime,endTime);
            //统计层级为片区
            rectificationRateByDistrict(factory,type,startTime,endTime);
            //统计层级为集团
            rectificationRateByGroup(factory,type,startTime,endTime);
            factory.close();
        }catch (Exception e){
            if (null!=factory)
                factory.close(false);
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
        }
    }

    /**
     * 设置kpi指标的通用数据值
     * @param template
     * @param type 日期类型，1代表是月份，2代表是季度，3代表是年
     * @param date 日期
     * @return
     */
    private KpiStatistics generateKpiStatistics(KPITemplate template,Integer type,Date date){
        KpiStatistics kpiStatistics=new KpiStatistics();
        kpiStatistics.setKpiId(template.getId());
        kpiStatistics.setKpiCode(template.getCode());
        kpiStatistics.setKpiName(template.getName());
        //判断如何设置日期，1代表是月份，2代表是季度，3代表是年
        kpiStatistics.setDateType(type);
        kpiStatistics.setDateValue(getDateValue(type,date));
        return  kpiStatistics;
    }

    /**
     *根据日期和日期类型，获取相应的日期字符串
     * 月份返回形如2020-02，季度返回2020-1，年返回2020
     * @param type 日期类型，1代表是月份，2代表是季度，3代表是年
     * @param date  日期
     * @return
     */
    private String getDateValue(Integer type,Date date){
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(date);
        int year=calendar.get(Calendar.YEAR);
        int month=calendar.get(Calendar.MONTH)+1;
        switch (type){
            case 1:
                return ""+year+"-"+(month<10?"0"+month:month);
            case 2:
                return ""+year+"-"+(month/3+1);
            case 3:
                return year+"";
            default:
                return "";
        }
    }

    /**
     * 统计层级为个人，
     * 计算隐患整改数
     * 当传入隐患整改状态为已整改时，计算隐患整改实际完成总数,指标库code:0077
     * 当未传入隐患整改状态时，计算隐患整改计划完成总数,指标库code:0078
     * @param factory
     * @param type 日期类型，1代表是月份，2代表是季度，3代表是年
     * @param startTime 统计的开始时间
     * @param endTime 统计的结束时间
     * @param alreadyReformId 隐患整改状态，这里只关注2种值，当传入已整改状态，和未传入时
     * @param kpiTemplateCode 指标库code
     */
    private void rectificationFinishedOrTotalByPerson(SessionFactory factory,Integer type,Date startTime,Date endTime,
                                                      String alreadyReformId,String kpiTemplateCode) throws Exception {
        IndicationItemsMapper itemsMapper=factory.getMapper(IndicationItemsMapper.class);
        DangerRectificationStatisticMapper dangerRectificationStatisticMapper=factory.getMapper(DangerRectificationStatisticMapper.class);
        KpiStatisticsMapper statisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
        //统计层级为员工个人，统计已完成整改数量
        List<DangerRectificationStatistics> finishedList=dangerRectificationStatisticMapper.countRectificationByPerson(alreadyReformId,
                startTime,endTime);
        //构建统计隐患整改实际完成总数实体类
        List<KpiStatistics> kpiStatisticsList=null;
        //获取当前统计指标实体类
        KPITemplate kpiTemplate=factory.getMapper(KPITemplateMapper.class).queryTemplateByCode(kpiTemplateCode);
        if (null!=finishedList&&finishedList.size()>0){
            kpiStatisticsList=new ArrayList<>();
            Date date=new Date();
            for(DangerRectificationStatistics statistics:finishedList){
                KpiStatistics kpiStatistics=generateKpiStatistics(kpiTemplate,type,startTime);
                kpiStatistics.setObjectId(statistics.getCode().split("_")[0]);
                kpiStatistics.setObjectName(statistics.getName().split("_")[0]);
                kpiStatistics.setKpiValue(Float.parseFloat(statistics.getTotal().toString()));
                kpiStatistics.setStatisticalType(1);
                kpiStatistics.setAddTime(date);
                kpiStatisticsList.add(kpiStatistics);
            }
        }
        //执行批量插入操作
        if(null!=kpiStatisticsList&&kpiStatisticsList.size()>0){
            Integer value=statisticsMapper.batchInsert(kpiStatisticsList);
            if (value<0){
                SimpleDateFormat format=new SimpleDateFormat();
                String a=type==2?getDateValue(type,startTime):format.format(startTime);
                throw new Exception(a+"计算指标库code为"+kpiTemplateCode+
                        "，统计层级为员工失败");
            }
        }
    }

    /**
     * 统计层级为部门
     * 计算隐患整改实际总数或者计算隐患整改计划总数
     * 当传入隐患整改状态为已整改时，计算隐患整改实际完成总数,指标库code:0077
     * 当未传入隐患整改状态时，计算隐患整改计划完成总数,指标库code:0078
     * @param factory
     * @param type 日期类型，1代表是月份，2代表是季度，3代表是年
     * @param startTime 统计的开始时间
     * @param endTime 统计的结束时间
     * @param alreadyReformId 隐患整改状态，这里只关注2种值，当传入已整改状态，和未传入时
     * @param kpiTemplateCode 指标库code
     */
    private void rectificationFinishedOrToTalByDept(SessionFactory factory,Integer type,Date startTime,Date endTime,String alreadyReformId,
                                                    String kpiTemplateCode) throws Exception {
        IndicationItemsMapper itemsMapper=factory.getMapper(IndicationItemsMapper.class);
        DangerRectificationStatisticMapper dangerRectificationStatisticMapper=factory.getMapper(DangerRectificationStatisticMapper.class);
        KpiStatisticsMapper statisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
        //先获取当前组织架构上所有的部门
        List<DepartmentTreeBean> departmentTreeBeanList= (List<DepartmentTreeBean>) util.depttree("c75d5edacbc042448dab01951208421b",1).getData();
        if (null==departmentTreeBeanList||departmentTreeBeanList.size()<=0){
            return;
        }
        //获取当前标志为水司的部门（组织架构）
        List<CorpBean> corpBeanList=corpManagementService.corpBeanList();
        //先排除集团 将当前获取的所有部门排除当前为水司，以及当前集团的的code
        List<DepartmentTreeBean> departmentTreeBeanList1=null;
        departmentTreeBeanList1=departmentTreeBeanList.stream().filter(d->!d.getDepartmentCode().equals("c75d5edacbc042448dab01951208421b")).collect(Collectors.toList());
        //再排除水司
        List<String> corpCodeList=corpBeanList.stream().map(CorpBean::getCorpCode).collect(Collectors.toList());
        List<DepartmentTreeBean> result=null;
        result=departmentTreeBeanList1.stream().filter(d->!(corpCodeList.contains(d.getDepartmentCode()))).collect(Collectors.toList());
        //循环查询每个部门下有多少个整改隐患
        Date date=new Date();
        List<KpiStatistics> kpiStatisticsList=new ArrayList<>();
        for(DepartmentTreeBean departmentTreeBean:result){
            //查询该部门下所有子部门以及所有网格
            MessageBean<?> msg=gridNodeService.childList(departmentTreeBean.getDepartmentCode(),1);
            //存储部门和网格code
            List<String> codeList=new ArrayList<>();
            if (msg.getData()!=null) {
                List<Map<String,String>> mapList= (List<Map<String, String>>) msg.getData();
                codeList=mapList.stream().map(m->m.get("code")).collect(Collectors.toList());
            }else{
                codeList.add(departmentTreeBean.getDepartmentCode());
            }
            //查询统计值
            Integer total=dangerRectificationStatisticMapper.countRectificationByDept(alreadyReformId,startTime,endTime,codeList);
            if (total>0){
                //获取当前统计指标实体类
                KPITemplate kpiTemplate=factory.getMapper(KPITemplateMapper.class).queryTemplateByCode(kpiTemplateCode);
                KpiStatistics kpiStatistics=generateKpiStatistics(kpiTemplate,type,startTime);
                kpiStatistics.setObjectId(departmentTreeBean.getDepartmentCode());
                kpiStatistics.setObjectName(departmentTreeBean.getName());
                kpiStatistics.setKpiValue(Float.parseFloat(total.toString()));
                kpiStatistics.setStatisticalType(2);
                kpiStatistics.setAddTime(date);
                kpiStatisticsList.add(kpiStatistics);
            }
        }
        //执行批量插入操作
        if(null!=kpiStatisticsList&&kpiStatisticsList.size()>0){
            Integer value=statisticsMapper.batchInsert(kpiStatisticsList);
            if (value<0){
                SimpleDateFormat format=new SimpleDateFormat();
                String a=type==2?getDateValue(type,startTime):format.format(startTime);
                throw new Exception(a+"计算指标库code为"+kpiTemplateCode+
                        "，统计层级为部门失败");
            }
        }
    }

    /**
     * 统计层级为水司
     * 计算隐患整改实际总数或者计算隐患整改计划总数
     * 当传入隐患整改状态为已整改时，计算隐患整改实际完成总数,指标库code:0077
     * 当未传入隐患整改状态时，计算隐患整改计划完成总数,指标库code:0078
     * @param factory
     * @param type 日期类型，1代表是月份，2代表是季度，3代表是年
     * @param startTime 统计的开始时间
     * @param endTime 统计的结束时间
     * @param alreadyReformId 隐患整改状态，这里只关注2种值，当传入已整改状态，和未传入时
     * @param kpiTemplateCode 指标库code
     */
    private void rectificationFinishedOrTotalByCorp(SessionFactory factory,Integer type,Date startTime,Date endTime,String alreadyReformId,
                                                    String kpiTemplateCode) throws Exception {
        IndicationItemsMapper itemsMapper=factory.getMapper(IndicationItemsMapper.class);
        DangerRectificationStatisticMapper dangerRectificationStatisticMapper=factory.getMapper(DangerRectificationStatisticMapper.class);
        KpiStatisticsMapper statisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
        //统计层级为员工个人，统计已完成整改数量
        List<DangerRectificationStatistics> finishedList=dangerRectificationStatisticMapper.countRectificationByCorp(alreadyReformId,
                startTime,endTime);
        //构建统计隐患整改实际完成总数实体类
        List<KpiStatistics> kpiStatisticsList=null;
        //获取当前统计指标实体类
        KPITemplate kpiTemplate=factory.getMapper(KPITemplateMapper.class).queryTemplateByCode(kpiTemplateCode);
        if (null!=finishedList&&finishedList.size()>0){
            kpiStatisticsList=new ArrayList<>();
            Date date=new Date();
            for(DangerRectificationStatistics statistics:finishedList){

                KpiStatistics kpiStatistics=generateKpiStatistics(kpiTemplate,type,startTime);
                kpiStatistics.setObjectId(statistics.getCode());
                CorpBean corpBean=corpManagementService.getOne(statistics.getCode()).getData();
                kpiStatistics.setObjectName(corpBean.getCorpName());
                kpiStatistics.setKpiValue(Float.parseFloat(statistics.getTotal().toString()));
                kpiStatistics.setStatisticalType(3);
                kpiStatistics.setAddTime(date);
                kpiStatisticsList.add(kpiStatistics);
            }
        }
        //执行批量插入操作
        if(null!=kpiStatisticsList&&kpiStatisticsList.size()>0){
            Integer value=statisticsMapper.batchInsert(kpiStatisticsList);
            if (value<0){
                SimpleDateFormat format=new SimpleDateFormat();
                String a=type==2?getDateValue(type,startTime):format.format(startTime);
                throw new Exception(a+"计算指标库code为"+kpiTemplateCode+
                        "，统计层级为水司失败");
            }
        }
    }

    /**
     * 统计层级为片区
     * 计算隐患整改实际总数或者计算隐患整改计划总数
     * 当传入隐患整改状态为已整改时，计算隐患整改实际完成总数,指标库code:0077
     * 当未传入隐患整改状态时，计算隐患整改计划完成总数,指标库code:0078
     * @param factory
     * @param type 日期类型，1代表是月份，2代表是季度，3代表是年
     * @param startTime 统计的开始时间
     * @param endTime 统计的结束时间
     * @param alreadyReformId 隐患整改状态，这里只关注2种值，当传入已整改状态，和未传入时
     * @param kpiTemplateCode 指标库code
     */
    private void rectificationFinishedOrToTalByDistrict(SessionFactory factory,Integer type,Date startTime,Date endTime,String alreadyReformId,
                                                        String kpiTemplateCode) throws Exception {
        IndicationItemsMapper itemsMapper=factory.getMapper(IndicationItemsMapper.class);
        DangerRectificationStatisticMapper dangerRectificationStatisticMapper=factory.getMapper(DangerRectificationStatisticMapper.class);
        KpiStatisticsMapper statisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
        //获取当前统计指标实体类
        KPITemplate kpiTemplate=factory.getMapper(KPITemplateMapper.class).queryTemplateByCode(kpiTemplateCode);
        DistrictMapper districtMapper=factory.getMapper(DistrictMapper.class);
        List<KpiStatistics> kpiStatisticsList=new ArrayList<>();
        //查询当前所有片区
        List<District> districtList=districtMapper.queryAllDistrict(null,null);
        if(null!=districtList&&districtList.size()>0){
            Date date=new Date();
            for(District district:districtList){
                List<DistrictCorpRelation> relationList=districtService.queryDistrictCorp(district.getCode(),null,null).getData().getList();
                List<String> corpCodeList=new ArrayList<>();
                corpCodeList=relationList.stream().map(DistrictCorpRelation::getCorpCode).collect(Collectors.toList());
                Integer total=0;
                if (null!=corpCodeList&&corpCodeList.size()>0){
                    total=dangerRectificationStatisticMapper.countRectificationByGroupOrDistrict(alreadyReformId,startTime,endTime,corpCodeList);
                }
                if (total>0){
                    KpiStatistics kpiStatistics=generateKpiStatistics(kpiTemplate,type,startTime);
                    kpiStatistics.setObjectId(district.getCode());
                    kpiStatistics.setObjectName(district.getName());
                    kpiStatistics.setStatisticalType(3);
                    kpiStatistics.setAddTime(date);
                    kpiStatistics.setKpiValue(Float.parseFloat(total.toString()));
                    kpiStatisticsList.add(kpiStatistics);
                }
            }
        }
        //执行批量插入操作
        if(null!=kpiStatisticsList&&kpiStatisticsList.size()>0){
            Integer value=statisticsMapper.batchInsert(kpiStatisticsList);
            if (value<0){
                SimpleDateFormat format=new SimpleDateFormat();
                String a=type==2?getDateValue(type,startTime):format.format(startTime);
                throw new Exception(a+"计算指标库code为"+kpiTemplateCode+
                        "，统计层级为片区失败");
            }
        }
    }

    /**
     * 统计层级为集团
     * 计算隐患整改实际总数或者计算隐患整改计划总数
     * 当传入隐患整改状态为已整改时，计算隐患整改实际完成总数,指标库code:0077
     * 当未传入隐患整改状态时，计算隐患整改计划完成总数,指标库code:0078
     * @param factory
     * @param type 日期类型，1代表是月份，2代表是季度，3代表是年
     * @param startTime 统计的开始时间
     * @param endTime 统计的结束时间
     * @param alreadyReformId 隐患整改状态，这里只关注2种值，当传入已整改状态，和未传入时
     * @param kpiTemplateCode 指标库code
     */
    private void rectificationFinishedOrTotalByGroup(SessionFactory factory,Integer type,Date startTime,Date endTime,String alreadyReformId,
                                                     String kpiTemplateCode) throws Exception {
        IndicationItemsMapper itemsMapper=factory.getMapper(IndicationItemsMapper.class);
        DangerRectificationStatisticMapper dangerRectificationStatisticMapper=factory.getMapper(DangerRectificationStatisticMapper.class);
        KpiStatisticsMapper statisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
        //获取当前统计指标实体类
        KPITemplate kpiTemplate=factory.getMapper(KPITemplateMapper.class).queryTemplateByCode(kpiTemplateCode);
        List<KpiStatistics> kpiStatisticsList=new ArrayList<>();
        Date date=new Date();
        KpiStatistics kpiStatistics=generateKpiStatistics(kpiTemplate,type,startTime);
        kpiStatistics.setObjectId("c75d5edacbc042448dab01951208421b");
        kpiStatistics.setObjectName("粤海水资源");
        kpiStatistics.setStatisticalType(5);
        kpiStatistics.setAddTime(date);
        Integer total=dangerRectificationStatisticMapper.countRectificationByGroupOrDistrict(alreadyReformId,startTime,endTime,null);
        kpiStatistics.setKpiValue(Float.parseFloat(total.toString()));
        kpiStatisticsList.add(kpiStatistics);
        //执行批量插入操作
        if(null!=kpiStatisticsList&&kpiStatisticsList.size()>0){
            Integer value=statisticsMapper.batchInsert(kpiStatisticsList);
            if (value<0){
                SimpleDateFormat format=new SimpleDateFormat();
                String a=type==2?getDateValue(type,startTime):format.format(startTime);
                throw new Exception(a+"计算指标库code为"+kpiTemplateCode+
                        "，统计层级为集团失败");
            }
        }
    }

    /**
     * 隐患整改率,指标库编码为：0034
     *  统计层级为员工个人
     * @param factory
     * @param type 日期类型，1代表是月份，2代表是季度，3代表是年
     * @param startTime 统计的开始时间
     * @param endTime 统计的结束时间
     */
    private void rectificationRateByPerson(SessionFactory factory,Integer type,Date startTime,Date endTime) throws Exception {
        IndicationItemsMapper itemsMapper=factory.getMapper(IndicationItemsMapper.class);
        DangerRectificationStatisticMapper dangerRectificationStatisticMapper=factory.getMapper(DangerRectificationStatisticMapper.class);
        KpiStatisticsMapper statisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
        //先去统计表中查询隐患计划整改的总数
        //查询已整改的指标字典数据的id
        String alreadyReformId=itemsMapper.matchIndicationItems("隐患整改状态","已整改")==null?null:
                itemsMapper.matchIndicationItems("隐患整改状态","已整改").getId();
        if(StringUtils.isEmpty(alreadyReformId)){
            return ;
        }
        //统计层级为员工个人，统计计划整改数量
        List<DangerRectificationStatistics> totalList=dangerRectificationStatisticMapper.countRectificationByPerson(null,
                startTime,endTime);
        //统计层级为员工个人，统计已经整改数量
        List<DangerRectificationStatistics> finishedList=dangerRectificationStatisticMapper.countRectificationByPerson(alreadyReformId,
                startTime,endTime);
        //获取指标库数据
        KPITemplate kpiTemplate=factory.getMapper(KPITemplateMapper.class).queryTemplateByCode("0034");
        //s收集隐患整改率要插入的数据
        List<KpiStatistics> kpiStatisticsList=null;
        if (null!=totalList&&totalList.size()>0){
            kpiStatisticsList=new ArrayList<>();
            Date date=new Date();
            for(DangerRectificationStatistics statistics:totalList){
                //确保分母不为0
                if (statistics.getTotal()>0){
                    KpiStatistics kpiStatistics=generateKpiStatistics(kpiTemplate,type,startTime);
                    kpiStatistics.setObjectId(statistics.getCode().split("_")[0]);
                    kpiStatistics.setObjectName(StringUtils.isNotEmpty(statistics.getName())?statistics.getName().split("_")[0]:"");
                    List<DangerRectificationStatistics> statisticsList=new ArrayList<>();
                    statisticsList=finishedList.stream().filter(
                            d->d.getCode().equals(statistics.getCode())).collect(Collectors.toList());
                    if (statisticsList!=null&&statisticsList.size()>0){
                        Float result=Float.parseFloat(statisticsList.get(0).getTotal().toString())/statistics.getTotal();
                        kpiStatistics.setKpiValue(result);
                    }else{
                        kpiStatistics.setKpiValue(0F);
                    }
                    kpiStatistics.setStatisticalType(1);
                    kpiStatistics.setAddTime(date);
                    kpiStatisticsList.add(kpiStatistics);
                }
            }
        }
        //执行批量插入操作
        if(null!=kpiStatisticsList&&kpiStatisticsList.size()>0){
            Integer value=statisticsMapper.batchInsert(kpiStatisticsList);
            if (value<0){
                SimpleDateFormat format=new SimpleDateFormat();
                String a=type==2?getDateValue(type,startTime):format.format(startTime);
                throw new Exception(a+"计算指标库code为0034，统计层级为员工失败");
            }
        }
    }

    /**
     * 隐患整改率,指标库编码为：0034
     * 统计层级为部门
     * @param factory
     * @param type 日期类型，1代表是月份，2代表是季度，3代表是年
     * @param startTime 统计的开始时间
     * @param endTime 统计的结束时间
     */
    private void rectificationRateByDept(SessionFactory factory,Integer type,Date startTime,Date endTime) throws Exception {
        IndicationItemsMapper itemsMapper=factory.getMapper(IndicationItemsMapper.class);
        DangerRectificationStatisticMapper dangerRectificationStatisticMapper=factory.getMapper(DangerRectificationStatisticMapper.class);
        KpiStatisticsMapper statisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
        //查询已整改的指标字典数据的id
        String alreadyReformId=itemsMapper.matchIndicationItems("隐患整改状态","已整改")==null?null:
                itemsMapper.matchIndicationItems("隐患整改状态","已整改").getId();
        if(StringUtils.isEmpty(alreadyReformId)){
            return ;
        }
        //先获取当前组织架构上所有的部门
        List<DepartmentTreeBean> departmentTreeBeanList= (List<DepartmentTreeBean>) util.depttree("c75d5edacbc042448dab01951208421b",1).getData();
        if (null==departmentTreeBeanList||departmentTreeBeanList.size()<=0){
            return;
        }

        //获取当前标志为水司的部门（组织架构）
        List<CorpBean> corpBeanList=corpManagementService.corpBeanList();
        //将当前获取的所有部门排除当前为水司，以及当前集团的的code，先排除集团
        List<DepartmentTreeBean> departmentTreeBeanList1=null;
        departmentTreeBeanList1=departmentTreeBeanList.stream().filter(d->!d.getDepartmentCode().equals("c75d5edacbc042448dab01951208421b")).collect(Collectors.toList());
        //再排除水司
        List<String> corpCodeList=corpBeanList.stream().map(CorpBean::getCorpCode).collect(Collectors.toList());
        List<DepartmentTreeBean> result=null;
        result=departmentTreeBeanList1.stream().filter(d->!(corpCodeList.contains(d.getDepartmentCode()))).collect(Collectors.toList());
        //循环查询每个部门下有多少个整改隐患
        Date date=new Date();
        List<KpiStatistics> kpiStatisticsList=new ArrayList<>();
        for(DepartmentTreeBean departmentTreeBean:result){
            //查询该部门下所有子部门以及所有网格
            MessageBean<?> msg=gridNodeService.childList(departmentTreeBean.getDepartmentCode(),1);
            //存储部门和网格code
            List<String> codeList=new ArrayList<>();
            if (msg.getData()!=null) {
                List<Map<String,String>> mapList= (List<Map<String, String>>) msg.getData();

                codeList=mapList.stream().map(m->m.get("code")).collect(Collectors.toList());
            }else{
                codeList.add(departmentTreeBean.getDepartmentCode());
            }
            //查询统计值
            Integer total=dangerRectificationStatisticMapper.countRectificationByDept(null,startTime,endTime,codeList);
            if(total>0){
                Integer actual=dangerRectificationStatisticMapper.countRectificationByDept(alreadyReformId,startTime,endTime,codeList);
                //获取当前统计指标实体类
                KPITemplate kpiTemplate=factory.getMapper(KPITemplateMapper.class).queryTemplateByCode("0034");
                KpiStatistics kpiStatistics=generateKpiStatistics(kpiTemplate,type,startTime);
                kpiStatistics.setObjectId(departmentTreeBean.getDepartmentCode());
                kpiStatistics.setObjectName(departmentTreeBean.getName());
                kpiStatistics.setKpiValue(Float.parseFloat(actual.toString())/total);
                kpiStatistics.setStatisticalType(2);
                kpiStatistics.setAddTime(date);
                kpiStatisticsList.add(kpiStatistics);
            }
        }
        //执行批量插入操作
        if(null!=kpiStatisticsList&&kpiStatisticsList.size()>0){
            Integer value=statisticsMapper.batchInsert(kpiStatisticsList);
            if (value<0){
                SimpleDateFormat format=new SimpleDateFormat();
                String a=type==2?getDateValue(type,startTime):format.format(startTime);
                throw new Exception(a+"计算指标库code为0034，统计层级为部门失败");
            }
        }
    }

    /**
     * 隐患整改率,指标库编码为：0034
     * 统计层级为水司
     * @param factory
     * @param type 日期类型，1代表是月份，2代表是季度，3代表是年
     * @param startTime 统计的开始时间
     * @param endTime 统计的结束时间
     */
    private void rectificationRateByCorp(SessionFactory factory,Integer type,Date startTime,Date endTime) throws Exception {
        IndicationItemsMapper itemsMapper=factory.getMapper(IndicationItemsMapper.class);
        DangerRectificationStatisticMapper dangerRectificationStatisticMapper=factory.getMapper(DangerRectificationStatisticMapper.class);
        KpiStatisticsMapper statisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
        //先去统计表中查询隐患计划整改的总数
        //查询已整改的指标字典数据的id
        String alreadyReformId=itemsMapper.matchIndicationItems("隐患整改状态","已整改")==null?null:
                itemsMapper.matchIndicationItems("隐患整改状态","已整改").getId();
        if(StringUtils.isEmpty(alreadyReformId)){
            return ;
        }
        //统计层级为员工个人，统计计划整改数量
        List<DangerRectificationStatistics> totalList=dangerRectificationStatisticMapper.countRectificationByCorp(null,
                startTime,endTime);
        //统计层级为员工个人，统计已经整改数量
        List<DangerRectificationStatistics> finishedList=dangerRectificationStatisticMapper.countRectificationByCorp(alreadyReformId,
                startTime,endTime);
        //获取指标库数据
        KPITemplate kpiTemplate=factory.getMapper(KPITemplateMapper.class).queryTemplateByCode("0034");
        //s收集隐患整改率要插入的数据
        List<KpiStatistics> kpiStatisticsList=null;
        if (null!=totalList&&totalList.size()>0&&null!=finishedList&&finishedList.size()>0){
            kpiStatisticsList=new ArrayList<>();
            Date date=new Date();
            for(DangerRectificationStatistics statistics:totalList){
                KpiStatistics kpiStatistics=generateKpiStatistics(kpiTemplate,type,startTime);
                kpiStatistics.setObjectId(statistics.getCode());
                kpiStatistics.setObjectName(statistics.getName());
                List<DangerRectificationStatistics> statisticsList=new ArrayList<>();
                statisticsList=finishedList.stream().filter(
                        d->d.getCode().equals(statistics.getCode())).collect(Collectors.toList());
                if (statisticsList!=null&&statisticsList.size()>0){
                    Float result=Float.parseFloat(statisticsList.get(0).getTotal().toString())/statistics.getTotal();
                    kpiStatistics.setKpiValue(result);
                }else{
                    kpiStatistics.setKpiValue(0F);
                }
                kpiStatistics.setStatisticalType(3);
                kpiStatistics.setAddTime(date);
                kpiStatisticsList.add(kpiStatistics);
            }
        }
        //执行批量插入操作
        if(null!=kpiStatisticsList&&kpiStatisticsList.size()>0){
            Integer value=statisticsMapper.batchInsert(kpiStatisticsList);
            if (value<0){
                SimpleDateFormat format=new SimpleDateFormat();
                String a=type==2?getDateValue(type,startTime):format.format(startTime);
                throw new Exception(a+"计算指标库code为0034，统计层级为水司失败");
            }
        }
    }

    /**
     * 隐患整改率,指标库编码为：0034
     * 统计层级为片区
     * @param factory
     * @param type 日期类型，1代表是月份，2代表是季度，3代表是年
     * @param startTime 统计的开始时间
     * @param endTime 统计的结束时间
     */
    private void rectificationRateByDistrict(SessionFactory factory,Integer type,Date startTime,Date endTime) throws Exception {
        IndicationItemsMapper itemsMapper=factory.getMapper(IndicationItemsMapper.class);
        DangerRectificationStatisticMapper dangerRectificationStatisticMapper=factory.getMapper(DangerRectificationStatisticMapper.class);
        KpiStatisticsMapper statisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
        //查询已整改的指标字典数据的id
        String alreadyReformId=itemsMapper.matchIndicationItems("隐患整改状态","已整改")==null?null:
                itemsMapper.matchIndicationItems("隐患整改状态","已整改").getId();
        if(StringUtils.isEmpty(alreadyReformId)){
            return ;
        }
        //获取当前统计指标实体类
        KPITemplate kpiTemplate=factory.getMapper(KPITemplateMapper.class).queryTemplateByCode("0034");
        DistrictMapper districtMapper=factory.getMapper(DistrictMapper.class);
        List<KpiStatistics> kpiStatisticsList=new ArrayList<>();
        //查询当前所有片区
        List<District> districtList=districtMapper.queryAllDistrict(null,null);
        if(null!=districtList&&districtList.size()>0){
            Date date=new Date();
            for(District district:districtList){
                List<DistrictCorpRelation> relationList=districtService.queryDistrictCorp(district.getCode(),null,null).getData().getList();
                List<String> corpCodeList=new ArrayList<>();
                corpCodeList=relationList.stream().map(DistrictCorpRelation::getCorpCode).collect(Collectors.toList());
                Integer total=0;
                Integer result=0;
                if (null!=corpCodeList&&corpCodeList.size()>0){
                    total=dangerRectificationStatisticMapper.countRectificationByGroupOrDistrict(null,startTime,endTime,corpCodeList);
                    //确认分母不为0，否则报错
                    if (total>0){
                        result=dangerRectificationStatisticMapper.countRectificationByGroupOrDistrict(alreadyReformId,startTime,endTime,corpCodeList);
                        KpiStatistics kpiStatistics=generateKpiStatistics(kpiTemplate,type,startTime);
                        kpiStatistics.setObjectId(district.getCode());
                        kpiStatistics.setObjectName(district.getName());
                        kpiStatistics.setStatisticalType(4);
                        kpiStatistics.setAddTime(date);
                        kpiStatistics.setKpiValue(Float.parseFloat(result.toString())/total);
                        kpiStatisticsList.add(kpiStatistics);
                    }
                }
            }
        }
        //执行批量插入操作
        if(null!=kpiStatisticsList&&kpiStatisticsList.size()>0){
            Integer value=statisticsMapper.batchInsert(kpiStatisticsList);
            if (value<0){
                SimpleDateFormat format=new SimpleDateFormat();
                String a=type==2?getDateValue(type,startTime):format.format(startTime);
                throw new Exception(a+"计算指标库code为0034，统计层级为片区失败");
            }
        }
    }

    /**
     * 隐患整改率,指标库编码为：0034
     * 统计层级为集团
     * @param factory
     * @param type 日期类型，1代表是月份，2代表是季度，3代表是年
     * @param startTime 统计的开始时间
     * @param endTime 统计的结束时间
     */
    private void rectificationRateByGroup(SessionFactory factory,Integer type,Date startTime,Date endTime) throws Exception {
        IndicationItemsMapper itemsMapper=factory.getMapper(IndicationItemsMapper.class);
        DangerRectificationStatisticMapper dangerRectificationStatisticMapper=factory.getMapper(DangerRectificationStatisticMapper.class);
        KpiStatisticsMapper statisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
        //查询已整改的指标字典数据的id
        String alreadyReformId=itemsMapper.matchIndicationItems("隐患整改状态","已整改")==null?null:
                itemsMapper.matchIndicationItems("隐患整改状态","已整改").getId();
        if(StringUtils.isEmpty(alreadyReformId)){
            return ;
        }
        //获取当前统计指标实体类
        KPITemplate kpiTemplate=factory.getMapper(KPITemplateMapper.class).queryTemplateByCode("0034");
        Date date=new Date();
        List<KpiStatistics> kpiStatisticsList=new ArrayList<>();
        KpiStatistics kpiStatistics=generateKpiStatistics(kpiTemplate,type,startTime);
        kpiStatistics.setObjectId("c75d5edacbc042448dab01951208421b");
        kpiStatistics.setObjectName("粤海水资源");
        kpiStatistics.setStatisticalType(5);
        kpiStatistics.setAddTime(date);
        Integer total=dangerRectificationStatisticMapper.countRectificationByGroupOrDistrict(null,startTime,endTime,null);
        Integer result=dangerRectificationStatisticMapper.countRectificationByGroupOrDistrict(alreadyReformId,startTime,endTime,null);
        kpiStatistics.setKpiValue(Float.parseFloat(result.toString())/total);
        kpiStatisticsList.add(kpiStatistics);
        //执行批量插入操作
        if(null!=kpiStatisticsList&&kpiStatisticsList.size()>0){
            Integer value=statisticsMapper.batchInsert(kpiStatisticsList);
            if (value<0){
                SimpleDateFormat format=new SimpleDateFormat();
                String a=type==2?getDateValue(type,startTime):format.format(startTime);
                throw new Exception(a+"计算指标库code为0034，统计层级为集团失败");
            }
        }
    }
}

